package com.atguigu.repservice.controller.front;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.commonutils.userVo.CommentUserVo;
import com.atguigu.repservice.entity.RepOrder;
import com.atguigu.repservice.entity.vo.OrderRequestVo;
import com.atguigu.repservice.entity.vo.RepOrderRequestVo;
import com.atguigu.repservice.entity.vo.RepOrderResponseVo;
import com.atguigu.repservice.service.RepOrderService;
import com.atguigu.repservice.service.RepSubjectService;
import com.atguigu.repservice.service.client.RepUserClient;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.netty.util.internal.MathUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ZhuangLiJiao
 * @since 2021-10-23
 */
@Api(description = "订单接口")
@RestController
@RequestMapping("/repservice/reporder")
@CrossOrigin
public class RepOrderController {

    @Autowired
    private RepOrderService orderService;

    @Autowired
    private RepUserClient userClient;

    @Autowired
    private RepSubjectService subjectService;


    //根据订单id查询订单信息
    @ApiOperation("根据订单id查询订单信息")
    @GetMapping("getOrderAllMessageById/{orderId}")
    public R getOrderAllMessageById(@PathVariable String orderId) {
        LambdaQueryWrapper<RepOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RepOrder::getId, orderId);
        RepOrder order = orderService.getOne(wrapper);
        order.setSubjectId(subjectService.getById(order.getSubjectId()).getTitle());
        order.setSubjectParentId(subjectService.getById(order.getSubjectParentId()).getTitle());
        return R.ok().data("item", order);
    }

    //设置订单交易成功状态
    @ApiOperation("设置订单交易成功状态")
    @GetMapping("setOrderStatusSuccess/{orderId}")
    public R setOrderStatusSuccess(@PathVariable String orderId) {
        LambdaQueryWrapper<RepOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RepOrder::getId, orderId);
        RepOrder order = orderService.getOne(wrapper);
        String totalFree = order.getFree();
        int all = Integer.parseInt(totalFree);
        double aYuan = all * 0.02;
        double bYuan = aYuan * 0.98;
        System.out.println("用户已经完支付：" + totalFree + "元。\n平台收取手续费：" + aYuan + "元");
        System.out.println("调用支付宝接口中......");
        System.out.println("发起转账");
        System.out.println("已打款到商家支付宝账户 " + bYuan + " 元");
        order.setStatus("5");//支付完成
        orderService.updateById(order);
        return R.ok();
    }

    //设置订单的交易额
    @ApiOperation("设置订单交易额")
    @GetMapping("setOrderMoney/{orderId}/{money}")
    public R setOrderMoney(@PathVariable("orderId") String orderId, @PathVariable("money") String money) {
        RepOrder order = orderService.getById(orderId);
        order.setFree(money);
        orderService.updateById(order);
        return R.ok();
    }

    //商家提供了维修服务
    @ApiOperation("商家完成了服务")
    @GetMapping("merchantFuWu/{orderId}")
    public R merchantFuWu(@PathVariable("orderId") String orderId) {
        RepOrder order = orderService.getById(orderId);
        order.setStatus("4");
        orderService.updateById(order);
        return R.ok();
    }

    //商家接受订单
    @ApiOperation("商家接受订单")
    @GetMapping("merchantJieDan/{orderId}/{userId}")
    public R merchantJieDan(@PathVariable("orderId") String orderId, @PathVariable("userId") String merchantId) {
        RepOrder order = orderService.getById(orderId);
        CommentUserVo merchant = userClient.getCommentUserById(merchantId);
        order.setMerchantId(merchant.getId());
        order.setMerchantShopName(merchant.getShopName());
        order.setMerchantMobile(merchant.getMobile());
        order.setMerchantNickname(merchant.getNickname());
        //设置为已经接单
        order.setStatus("3");
        orderService.updateById(order);
        return R.ok();
    }

    //1.创建订单：用户发起需求
    @ApiOperation("创建订单：用户发起需求")
    @PostMapping("userPublishOrder")
    public R userPublishOrder(@RequestBody RepOrderRequestVo.UserPublishOrder userPublishOrder, HttpServletRequest request) {
        String orderId = orderService.userPublishOrder(userPublishOrder, JwtUtils.getMemberIdByJwtToken(request));
        return R.ok();
    }

    //2.用户登录主状态
    @ApiOperation("创建订单：用户发起需求")
    @GetMapping("getLoginStatus")
    public R getLoginStatus(HttpServletRequest request) {
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        Boolean isLogin = false;

        if (!StringUtils.isEmpty(userId)) {
            isLogin = true;

            //通过id获取用户信息
            CommentUserVo commentUserVo = userClient.getCommentUserById(userId);

            return R.ok().data("isLogin", isLogin).data("object", commentUserVo);
        }
        return R.ok().data("isLogin", isLogin);
    }

    //修补：判断用户是否是商家
    @ApiOperation("修补：判断用户是否是商家")
    @GetMapping("getUserIsMerchant")
    public R getUserIsMerchant(HttpServletRequest request) {
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        Boolean isLogin = false;
        if (!StringUtils.isEmpty(userId)) {
            isLogin = true;

            //通过id获取用户信息
            CommentUserVo commentUserVo = userClient.getCommentUserById(userId);
            if (commentUserVo.getType().equals("2")) {
                return R.ok().data("getUserIsMerchant", "yes");
            }
        }
        return R.ok().data("getUserIsMerchant", "no");
    }


    //2.条件查询订单带分页的方法
    @ApiOperation("分页条件查询订单")
    @PostMapping("pageOrderConditionFront/{current}/{limit}")
    public R pageOrderCondition(@PathVariable("current") long current, @PathVariable("limit") long limit,
                                @RequestBody(required = false) OrderRequestVo.OrderQueryVo orderRequestVo) {
        //创建page对象
        Page<RepOrder> orderPage = orderService.pageOrderCondition(current, limit, orderRequestVo);
//        System.out.println("大小getSize："+orderPage.getSize());
//        System.out.println("大小Pages："+orderPage.getPages());
//        System.out.println("大小total："+orderPage.getTotal());.
        long total = orderPage.getTotal();//总记录数
        List<RepOrder> records = orderPage.getRecords(); //数据list集合
        List<RepOrderResponseVo.RepOrderPageQueryResponseVo> terminal = new ArrayList<>();

        for (RepOrder record : records) {
            RepOrderResponseVo.RepOrderPageQueryResponseVo vo = new RepOrderResponseVo.RepOrderPageQueryResponseVo();
            BeanUtils.copyProperties(record, vo);
            vo.setSubjectName(subjectService.getById(record.getSubjectId()).getTitle());
            vo.setSubjectParentName(subjectService.getById(record.getSubjectParentId()).getTitle());

            terminal.add(vo);
            System.out.println("每一条vo:" + vo);
            System.out.println(record);
        }

        return R.ok().data("total", total).data("rows", terminal);
    }

}

